import React, { useEffect } from 'react';
import { modifySysStatus, getSystemNode, getNodeUpdate } from '~/API/index';
import * as echarts from 'echarts';
import { Confirm, Message, Loading, Select } from '@knownsec/react-component';
import cn from 'classnames';
import i from '@/index.module.css';
import BreadCrumb from '@/components/BreadCrumb';
import s from './style.module.css';
import { getErrorMessage } from '@/common/constant';
// import SelectAnt from '@/components/SelectAnt';
import { get } from 'lodash-es';

export default function SystemLoad() {
  const [searchInfo, setSearchInfo] = React.useState('');
  const [deviceList, setDevice] = React.useState([]);
  const [updateTime, setUpdatetime] = React.useState('');
  const [showLoading, setShowLoading] = React.useState(true);
  const [statusData, setStatusData] = React.useState({
    cpu_percent: 0,
    cpu_percent_list: [],
    disk_business_percent:0,
    disk_business_percent_list:[],
    disk_data_percent: 0,
    disk_data_percent_list: [],
    disk_sys_percent: 0,
    disk_sys_percent_list: [],
    ip_addr: '10.10.10.10',
    last_update_time: '2021-07-06 12:23:12',
    mem_percent: 0,
    mem_percent_list: [],
    net_bytes_recv: 0,
    net_bytes_recv_list: [],
    net_bytes_sent: 0,
    net_bytes_sent_list: [],
    net_packets_recv: 0,
    net_packets_recv_list: [],
    net_packets_sent: 0,
    net_packets_sent_list: [],
    running_time: '0天',
  });
  useEffect(() => {
    getSysNode();
  }, []);
  const getSysNode = () => {
    getSystemNode().then((res) => {
        const is_cluster=JSON.parse(localStorage.info).is_cluster
      if (res.status == 'success') {
        const d = res.data?.node_list || [];
        d.map((v, index) => {
          v.label = v.node_ip + '(' + v.node_name + ')';
          v.value = index + '';
        });
        setDevice(d);
        setSearchInfo(0);
        const status=is_cluster?d[0].device_id:null
        getSysStatus(status);
        const ip=is_cluster?d[0].node_ip:res.data?.node_ip
        getdate(ip);
      }
      setShowLoading(false);
    });
  };
  const getdate = (ip) => {
    getNodeUpdate({ node_ip: ip }).then((res) => {
      if (res.status === 'success') {
        setUpdatetime(res.data);
      }
    });
  };
  const getSysStatus = (id) => {
    setShowLoading(true);
    const params={ qtype: 'system'}
    id&&(params.device_id=id)
    modifySysStatus(params)
      .then((res) => {
        setShowLoading(false);
        if (res.status === 'success') {
          setStatusData(res.data);
          const times = res.data.created_at;
          drawLine('cpu_percent', res.data.cpu_percent_list, 100, times);
          drawLine('disk_data_percent', res.data.disk_data_percent_list, 100, times);
          drawLine('disk_sys_percent', res.data.disk_sys_percent_list, 100, times);
          drawLine('mem_percent', res.data.mem_percent_list, 100, times);
          drawLine('disk_business_percent', res.data.disk_business_percent_list, 100, times);
        }
      })
      .catch((err) => {
        setShowLoading(false);
        if (err.hasOwnProperty('status')) {
          Message.show({ type: 'error', message: getErrorMessage(err) });
        }
      });
  };
  const drawLine = (id, data, num, dataX) => {
    const mayEcharts = echarts.init(document.getElementById(id));
    const option = {
      tooltip: {
        trigger: 'axis',
        formatter: (params) => {
          return `
            <div>
            <span style="display: inline-block; height: 6px; width: 6px; border-radius: 50%; background-color: #0b6fd6; margin-right: 5px; vertical-align: middle;"></span>
            <span style="margin-right: 20px; color: #333;">${params[0].name}</span>
            <span style="color: #333;">${params[0].value.toFixed(2)}%</span>
            </div>
          `;
        },
        extraCssText: 'background-color: #fff; border: 1px solid #ccc; box-shadow: 0 2px 4px #ccc;'
      },
      grid: {
        top: '10%',
        bottom: '30%',
        right: '3%',
        left: '70',
      },
      xAxis: {
        type: 'category',
        data: dataX,
      },
      yAxis: {
        type: 'value',
        show: false,
        max: num,
      },
      series: [
        {
          data,
          type: 'line',
          showSymbol: false,
        },
      ],
    };
    mayEcharts.setOption(option);
    window.addEventListener('resize', () => {
      mayEcharts.resize();
    });
  };
  const renderNum=(e)=>{
    const num= statusData[e]?statusData[e]:0
    return num.toFixed(2)
  }
  return (
    <div className={i.mainContent}>
      <BreadCrumb
        arr={[
          { link: '', name: '系统状态' },
          { link: '', name: '系统负载', active: true },
        ]}
      />
      <div className={cn(s.content, i.p24, i.oa, i.h100p, i.mins)}>
        <div className={s.bgc}>
          <div className={cn(i.p24, i.pr)}>
            <Loading show={showLoading} label="" />
            <div className={cn(i.df, i.aic, i.jcsb, s.pr)}>
              <div>
                {/* <svg
                  className={cn(i.vam)}
                  width="48px"
                  height="48px"
                  viewBox="0 0 48 48"
                  version="1.1"
                  xmlns="http://www.w3.org/2000/svg"
                  xlink="http://www.w3.org/1999/xlink"
                >
                  <g id="页面设计" stroke="none" strokeWidth="1" fill="none" fillRule="evenodd">
                    <g id="系统状态-系统负载" transform="translate(-184.000000, -171.000000)">
                      <g id="编组-11" transform="translate(184.000000, 171.000000)">
                        <circle
                          id="椭圆形备份-3"
                          stroke="#0B6FD6"
                          fillOpacity="0.1"
                          fill="#0B6FD6"
                          cx="24"
                          cy="24"
                          r="23.5"
                        ></circle>
                        <g
                          id="3.Icon/1.线性/2.业务安全类/负载均衡"
                          transform="translate(8.000000, 8.000000)"
                        >
                          <path
                            d="M25,5 L25,7 L24.586,7 L27.894,14 L29,14 L29,16 L26.909,16 L24,18.7573593 L21.09,16 L19,16 L19,14 L20.105,14 L23.412,7 L17,7 L16.999,25 L21,25 L21,27 L11,27 L11,25 L14.999,25 L15,7 L8.587,7 L11.894,14 L13,14 L13,16 L10.909,16 L8,18.7573593 L5.09,16 L3,16 L3,14 L4.105,14 L7.413,7 L7,7 L7,5 L25,5 Z M24,10.439 L22.316,14 L25.683,14 L24,10.439 Z M8,10.439 L6.316,14 L9.683,14 L8,10.439 Z"
                            id="形状"
                            fill="#0B6FD6"
                            fillRule="evenodd"
                          ></path>
                          <rect id="矩形" x="0" y="0" width="32" height="32"></rect>
                        </g>
                      </g>
                    </g>
                  </g>
                </svg> */}
                <span className={cn(i.vam)}>设备负载</span>
              </div>
              <div className={i.primaryColor}>
                <svg
                  className={i.vam}
                  width="14px"
                  height="16px"
                  viewBox="0 0 14 16"
                  version="1.1"
                  xmlns="http://www.w3.org/2000/svg"
                  xlink="http://www.w3.org/1999/xlink"
                >
                  <g id="页面设计" stroke="none" strokeWidth="1" fill="none" fillRule="evenodd">
                    <g id="系统状态-系统负载" transform="translate(-1104.000000, -203.000000)">
                      <g id="编组-6" transform="translate(1101.000000, 201.000000)">
                        <g id="icon/操作编辑类/刷新">
                          <path
                            d="M12.9826943,2.27133848 L14.8576943,5.51893375 L11.610099,7.39393375 L10.985099,6.31140199 L12.0676308,5.68640199 C12.1495439,5.63910944 12.2240794,5.5839458 12.2908334,5.52241801 C11.5772839,5.20332177 10.8016419,5.03623948 10,5.03623948 C6.89339828,5.03623948 4.375,7.55463776 4.375,10.6612395 C4.375,13.7678412 6.89339828,16.2862395 10,16.2862395 C13.0511267,16.2862395 15.5348696,13.8569809 15.6226018,10.8270909 L15.625,10.6612395 L16.875,10.6612395 C16.875,14.4581971 13.7969577,17.5362395 10,17.5362395 C6.20304235,17.5362395 3.125,14.4581971 3.125,10.6612395 C3.125,6.86428183 6.20304235,3.78623948 10,3.78623948 C10.9431705,3.78623948 11.8419814,3.97616507 12.6602741,4.31985738 C12.633225,4.20364706 12.5884339,4.08845946 12.5251625,3.97887024 L11.9001625,2.89633848 L12.9826943,2.27133848 Z"
                            id="路径"
                            fill="#999EA8"
                            fillRule="evenodd"
                          ></path>
                          <rect id="矩形" x="0" y="0" width="20" height="20"></rect>
                        </g>
                      </g>
                    </g>
                  </g>
                </svg>
                <span className={cn(i.vam, i.ml10)}>最近更新时间:</span>
                {/* statusData.last_update_time */}
                <span className={cn(i.ml10, i.vam)}>{updateTime}</span>
              </div>
            </div>
            {
            deviceList.length > 1 
            && (
                <div className={s.selBOX}>
                  <Select
                    pro
                    value={[searchInfo]}
                    placeholder="选择设备"
                    option={deviceList}
                    className={s.sel}
                    onChange={({ selectedItem }) => {
                      const e = selectedItem[0].value
                      setSearchInfo(e);
                      getSysStatus(deviceList[e].device_id);
                      setUpdatetime('');
                      getdate(deviceList[e].node_ip);
                    }}
                  />
                </div>
              )}
            <div className={i.pt30}>
              <p>CPU利用率: &nbsp;{renderNum('cpu_percent')}%</p>
              <div id="cpu_percent" className={cn(i.h100, s.newbors)}></div>
            </div>
            <div className={i.pt30}>
              <p>内存利用率: &nbsp;{renderNum('mem_percent')}%</p>
              <div id="mem_percent" className={cn(i.h100, s.newbors)}></div>
            </div>
            <div className={i.pt30}>
              <p>系统区硬盘利用率: &nbsp;{renderNum('disk_sys_percent')}%</p>
              <div id="disk_sys_percent" className={cn(i.h100, s.newbors)}></div>
            </div>
            <div className={i.pt30}>
              <p>数据区硬盘利用率: &nbsp;{renderNum('disk_data_percent')}%</p>
              <div id="disk_data_percent" className={cn(i.h100, s.newbors)}></div>
            </div>
            <div className={i.pt30}>
              <p>业务区硬盘利用率: &nbsp;{renderNum('disk_business_percent')}%</p>
              <div id="disk_business_percent" className={cn(i.h100, s.newbors)}></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
